const bluebird = require('bluebird');
const connectionModel = require('../models/connection');
// XSS 防御
var escapeHtml = function(str) {
	if (!str) return '';
	// 对&符号的转义只能放在最前面，否则之后转义后的&符号也会被转义
	str = str.replace(/&/g, '&amp;'); 
	str = str.replace(/</g, '&lt;');
	str = str.replace(/>/g, '&gt;');
	str= str.replace(/"/g, '&quto;');
	str= str.replace(/'/g, '&#39;');
	// 由于多个空格可能会后会显示为一个，对空格的转义可能造成显示问题
	// str= str.replace(/ /g, '&#32;');
	return str;
};

var escapeForJs = function(str) {
	if(!str) return '';
	str = str.replace(/\\/g, '\\\\');
	str = str.replace(/"/g, '\\"');
	return str;
};

// 富文本 黑名单
// var xssFilter = function(html) {
// 	if(!html) return '';
// 	html = html.replace(/<\s*\/?script>\s*/g, '');
// 	html = html.replace(/javascript:[^'"]*/g, '');
// 	html = html.replace(/onerror\s*=\s*['"]?[^'"]*['"]?/g, '');
// 	return html;
// };

//富文本 白名单
// var xssFilter = function(html) {
// 	if (!html) return '';
// 	var cheerio = require('cheerio');
// 	var $ = cheerio.load(html);

// 	// 白名单
// 	var whiteList = {
// 		'body':[],
// 		'html':[],
// 		'head':[],
// 		'img': ['src'],
// 		'font': ['color', 'size'],
// 		'a': ['href']
// 	};
// 	$('*').each(function(index, elem) {
// 		// console.log('this is elem:', elem);
// 		console.log('elem.name:', elem.name);
// 		if (!whiteList[elem.name]) {
			
// 			$(elem).remove();
// 			return;
// 		}
// 		for (var attr in elem.attribs) {
// 			if (whiteList[elem.name].indexOf(attr) === -1) {
// 				$(elem).attr(attr, null)
// 			}
// 		}
// 	});
// 	// console.log(html, $.html());
// 	return $.html();
// };

var xssFilter = function(html) {
	if (!html) return '';
	var xss = require('xss');
	var ret = xss(html);
	return ret;
};

exports.index = async function(ctx, next){
	const connection = connectionModel.getConnection();
	const query = bluebird.promisify(connection.query.bind(connection));
	const posts = await query(
			'select post.*,count(comment.id) as commentCount from post left join comment on post.id = comment.postId group by post.id limit 10'
		);
	const comments = await query(
			'select comment.*,post.id as postId,post.title as postTitle,user.username as username from comment left join post on comment.postId = post.id left join user on comment.userId = user.id order by comment.id desc limit 10'
		);
	ctx.render('index', {
		posts, 
		comments, 
		from: escapeHtml(ctx.query.from) || '',  // XSS防御
		fromForJs: JSON.stringify(ctx.query.from),
		avatarId: escapeHtml(ctx.query.avatarId || '')});
	connection.end();
};

exports.post = async function(ctx, next){
	try{
		console.log('enter post');

		const id = ctx.params.id;
		const connection = connectionModel.getConnection();
		const query = bluebird.promisify(connection.query.bind(connection));
		const posts = await query(
			`select * from post where id = "${id}"`
		);
		let post = posts[0];

		const comments = await query(
			`select comment.*,user.username from comment left join user on comment.userId = user.id where postId = "${post.id}" order by comment.createdAt desc`
		);
		comments.forEach(comment => {
			comment.content = xssFilter(comment.content);
		});
		if(post){
			ctx.render('post', {post, comments});
		}else{
			ctx.status = 404;
		}
		connection.end();
	}catch(e){
		console.log('[/site/post] error:', e.message, e.stack);
		ctx.body = {
			status: e.code || -1,
			body: e.message
		};
	}
};

exports.addComment = async function(ctx, next){
	try{
		const data = ctx.request.body;
		const connection = connectionModel.getConnection();
		const query = bluebird.promisify(connection.query.bind(connection));
		const result = await query(
			`insert into comment(userId,postId,content,createdAt) values("${ctx.cookies.get('userId')}", "${data.postId}", "${data.content}",${connection.escape(new Date())})`
		);
		if(result){
			ctx.redirect(`/post/${data.postId}`);
		}else{
			ctx.body = 'DB操作失败';
		}
	}catch(e){
		console.log('[/site/addComment] error:', e.message, e.stack);
		ctx.body = {
			status: e.code || -1,
			body: e.message
		};
	}
};
